﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_OrderRequest_SaleOrderRequestList : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadForm();
        }
    }
    private void loadForm()
    {
        //Load tinh thanh
        int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
        int isProvinceAll = (ProvinceID == 0 ? 1 : 0);
        Utils.loadLocation(cboProvinceIDSearch, 0, isProvinceAll, ProvinceID);
        //load Shop
        int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
        int isShopAll = (ShopID == 0 ? 1 : 0);
        Utils.loadShopByProvinceToCombo(cboShop, isShopAll, ProvinceID, ShopID, "");
        
        Utils.LoadCodeDetail(cboStatus, "SaleOderRequestStatus", 1);
        cboStatus.SelectedValue = "N";

        gv.DataSource = new DataTable();
        gv.DataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        LoadData();
        gv.DataBind();
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/SaleOrderRequestList", true);
    }

    protected void gvData_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        LoadData();
    }
    protected void gvData_ItemCommand(object sender, GridCommandEventArgs e)
    {

        try
        {
            string commandName = e.CommandName;
            GridDataItem item = e.Item as GridDataItem;
            String SaleOrderRequestID = e.CommandArgument.ToString();
            DBDataContext db = LINQUtil.GetDBWriteOnly();
            if (commandName == "DeleteItem")
            {
                var sor = db.SaleOrderRequests.FirstOrDefault(s => s.ID == int.Parse(SaleOrderRequestID));
                if (sor != null)
                {
                    sor.Status = 'E';
                    db.Update<SaleOrderRequest>(sor);
                    db.SubmitChanges();
                    JavascriptUtil.LoadMessage(UpdatePanel1, true, "Xóa thành công");
                    LoadData();
                    gv.DataBind();
                }
            }
            else if (commandName == "CreateItem")//tao don hang
            {
                Session["SaleOrderRequestID"] = SaleOrderRequestID;
                Session["Task"] = "createSOFromSOR";
                //check xem da tao don hang chua
                var check = db.SaleOrders.FirstOrDefault(a => a.SaleOrderRequestID == int.Parse(SaleOrderRequestID) && a.Status != 'E');
                if (check == null)
                {
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('" + ResolveUrl("~/SaleOrder") + "');", true);
                }
                else
                {
                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Đơn đặt hàng này đã được tạo đơn hàng trước đó");
                }
            }
            else if (commandName == "ViewItem")//xem chi tiet don dat hang
            {
                Session["SaleOrderRequestID"] = SaleOrderRequestID;
                ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('" + ResolveUrl("~/SaleOrderRequestDetail") + "');", true);
            }
            else if (commandName == "EditItem")//sua don dat hang
            {
                Session["SaleOrderRequestID"] = SaleOrderRequestID;
                ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('" + ResolveUrl("~/SaleOrderRequest") + "');", true);
            }
        }
        catch (Exception ex)
        {
            ControlUtil.LogError("----------------------------");
            ControlUtil.LogError("SaleOrderRequestList-gvData_ItemCommand");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("----------------------------");
        }
    }

    protected void gv_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = (GridDataItem)e.Item;
            string status = item["StatusCode"].Text.ToString();
            Button DeleteCol = (Button)item.FindControl("btnDelete");
            Button CreateCol = (Button)item.FindControl("btnCreateOrder");
            Button EditCol = (Button)item.FindControl("btnEdit");
            if (status != "N")
            {
                DeleteCol.Visible = false;
                CreateCol.Visible = false;
                EditCol.Visible = false;
            }
        }
    }
    private void LoadData()
    {
        try
        {
            DBDataContext db = LINQUtil.GetDBWriteOnly();
            String Status = this.cboStatus.SelectedValue;
            int ProvinceID = int.Parse(this.cboProvinceIDSearch.SelectedValue == "" ? "0" : this.cboProvinceIDSearch.SelectedValue);
            String Shop = this.cboShop.SelectedValue;
            String SaleOrderCode = this.txtSaleOrderCode.Text.Trim();
            String Customer = this.txtCustomerName.Text.Trim();
            String Product = this.txtProduct.Text.Trim();
            String PersonReceipt = this.txtReceiptPerson.Text.Trim();
            String PersonPhone = this.txtReceiptPhoneNumer.Text.Trim();
            String PersonAddress = this.txtReceiptAdress.Text.Trim();
            DateTime FromDate = new DateTime(2014, 06, 01);
            if (this.dtpFromDate.SelectedDate != null)
            {
                FromDate = this.dtpFromDate.SelectedDate.Value;
            }
            DateTime ToDate = new DateTime(2099, 12, 31);
            if (this.dtpToDate.SelectedDate != null)
            {
                ToDate = this.dtpToDate.SelectedDate.Value;
            }
            int PageNumber = gv.CurrentPageIndex + 1;
            int PageSize = gv.PageSize;
            var q = db.SaleOrderRequest_Search(SaleOrderCode, Status,ProvinceID, int.Parse(Shop), Customer, Product, PersonReceipt, PersonPhone, PersonAddress, FromDate, ToDate, PageSize, PageNumber).ToList();
            if (q.Count > 0)
            {
                gv.Height = 180;
                gv.ClientSettings.Scrolling.AllowScroll = true;
                gv.ClientSettings.Scrolling.UseStaticHeaders = true;
                gv.VirtualItemCount = q[0].TotalRows.Value;
                gv.DataSource = q;
            }
            else
            {
                gv.DataSource = new DataTable();
            }
        }catch(Exception ex){
            ControlUtil.LogError("----------------------------");
            ControlUtil.LogError("SaleOrderRequestList-LoadData");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("----------------------------");
        }
    }

    protected void cboProvinceIDSearch_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        int ProvinceID = int.Parse(this.cboProvinceIDSearch.SelectedValue == "" ? "0" : this.cboProvinceIDSearch.SelectedValue);
        Utils.loadShopByProvinceToCombo(cboShop, 1, ProvinceID, 0, "");
    }
}